<?php
/*
 * 客户控制器
 */
header("Content-Type: text/html;charset=UTF-8");
class Customer extends CI_Controller {
	function __construct() {
		parent::__construct ();
		$this->load->helper ( 'url' );
		$this->load->library ( 'pagination' );
	}

	public function index($offset = 0,$error_info = '') {
		$user_name=$this->session->userdata('username');
		if($user_name){
			$this->load->model ( 'customer_model', 'customerm' );
			$limit = 10;
			$total = $this->customerm->count_nums ();
			$data['total']=$total;
			$data['offset']=$offset;
			$data ['customer'] = $this->customerm->list_customers ( $limit, $offset );

			$current_total=count($data ['customer']);
			$data['current_total']=$offset+$current_total;

			$config ['base_url'] = base_url () . 'index.php/customer/index/';
			$config ['total_rows'] = $total;
			$config ['per_page'] = $limit;
			$config ['num_links'] = 4;
			$config ['first_link'] = '首页';
			$config ['last_link'] = '尾页';
			$this->pagination->initialize ( $config );
			$data ['pag_links'] = $this->pagination->create_links ();

			$data ['page_title'] = '客户 — 昊美科技CRM系统';
			$data ['class1'] = 'cur';
			$data ['offset'] = $offset;
			/*查询顶级客户*/
			$q = $this->db->get_where('customer',array('parent_id' =>0));
			$data ['top_level'] = $q->result();
			$data ['all_users'] = $this->get_all_users();

			$data ['parent_customers'] = $this->get_parent_customer();
			$data ['error_info'] = $error_info;
			
			$this->load->view ( 'customer_list', $data );
		}else{
			$this->load->view ( 'login');
		}

	}

	public function find_error_drop($error_info){ /*添加,编辑出现条件不满足时调用*/
		$this->index(0,$error_info);
	}

	/*
	 * 客户名查询记录
	 */
	public function check($name = '',$top_level_id = ''){
		$this->db->like('customer_name', urldecode($name));
		if($top_level_id){
			$this->db->where('parent_id', $top_level_id);
		}
		$query = $this->db->get('customer');

// 		foreach ($query->result() as $row) { /*获取所有者*/
// 			$user_query = $this->db->get_where ( 'user', array ('id' => $row->user_id ) );
// 			$user = $user_query->row();
// 			$row->user_name = $user->user_name;

// 			$customers[] = $row;
// 		}
// 		for($i=0;$i<count($customers);$i++){ /*获取子级客户*/
// 			$parent_id = $customers[$i]->id;
// 			$sql = "select customer.*,user.user_name as user_name from customer inner join user on customer.user_id = user.id where parent_id = $parent_id";
// 			$county_query = $this->db->query($sql);
// 			$counties = $county_query->result();
// 			$customers[$i]->counties = $counties;
// 		}
		$data['customer'] =$query->result();
		$data['customer'][0]->cus_name_list = 'none';

		$data ['pag_links'] = '';
		$data ['cus_name_list'] = 'none';
		$data ['page_title'] = '客户 — 昊美科技CRM系统';
		$data ['class1'] = 'cur';
		$data ['all_users'] = $this->get_all_users();
		$this->load->view ( 'customer_list', $data );
	}

	/**
	 * 数据所有者查询
	 * */
	public function check_user_messages($id = ''){
		$customers = $this->list_user_customers($id);

// 		for($i=0;$i<count($customers);$i++){ /*获取子级客户*/
// 			$parent_id = $customers[$i]->parent_id;
// 			if(!$parent_id){
// 				$id = $customers[$i]->id;
// 				$sql = "select customer.*,user.user_name as user_name from customer inner join user on customer.user_id = user.id where parent_id = $id";
// 				$county_query = $this->db->query($sql);
// 				$counties = $county_query->result();
// 				$customers[$i]->counties = $counties;
// 			}
// 		}
		$data['customer'] = $customers;
		for($i=0;$i<count($data['customer']);$i++){
			$data['customer'][$i]->cus_name_list = 'none';
		}

		$data ['pag_links'] = '';
		$data ['page_title'] = '客户 — 昊美科技CRM系统';
		$data ['class1'] = 'cur';
		$data ['cus_name_list'] = 'none';
		$data ['all_users'] = $this->get_all_users();
		$query = $this->db->query('SELECT user_name FROM user where id = '.$id.'');
		$row = $query->row();
		$data ['check_user_name'] = $row->user_name;
		$data ['parent_customers'] = $this->get_parent_customer();

		$cus_count = count($data['customer']);
		$data ['check_cus_pag_links'] = '1';
		$data ['total'] = $cus_count;
		$data ['current_total'] = $cus_count;

		$this->load->view ( 'customer_list', $data );
	}

	/*
	 * 删除记录
	 */
	public function delete($id = '') {
		$this->db->delete ( 'customer', array ('id' => $id ) );
		redirect ( 'customer/index/' );
	}

	/*
	 * 查看某条记录
	 */
	public function find($id = '') {
		$this->db->select('*')->from('customer')->where('customer.id', $id);
		$query = $this->db->get();
		/*获取客户区域*/
		foreach ($query->result() as $row){
    		$region_id = $row->region_id;
		}
		if(!$row->region_id){
			$find_data['region_name'] = '未选区域';
		}else{
			$this->db->select('district')->from('region')->where('id', $row->region_id);
			$q = $this->db->get();
			$row = $q->result();
			foreach ($q->result() as $row){
    			$district = $row->district;
			}
			$find_data['region_name'] = $district;
		}

		$find_data['find_customer'] = $query->result();
		/*获取针对该客户的日程*/
		$q = $this->db->select('*')->from('schedule')->where('schedule.customer_id', $id);
		$q = $this->db->get();
		$find_data['find_schedules'] = $q->result();

		/*获取针对该客户的销售机会*/
		$q = $this->db->select('*')->from('opportunity')->where('opportunity.customer_id', $id);
		$q = $this->db->get();
		$find_data['find_opportunitys'] = $q->result();

		/*获取针对该客户的联系人*/
		$q = $this->db->select('*')->from('contacter')->where('contacter.customer_id', $id);
		$q = $this->db->get();
		$find_data['find_contacters'] = $q->result();

		/*获取针对该客户的合同*/
		$q = $this->db->select('customer.customer_name as customer_name,contract.*,opportunity.id as opportunity_id,opportunity.subject as opportunity_subject,user.user_name as user_name')->from('customer')->join('contract', 'contract.customer_id = customer.id')->join('opportunity', 'contract.opportunity_id = opportunity.id')->join('user','contract.owner_id=user.id')->where('contract.customer_id',$id);
		$q = $this->db->get();
		$find_data['find_contracts'] = $q->result();

		$this->load->view ( 'customer_view', $find_data );
	}

	/*
	 * 新增客户
	 */
	public function show_customer_add(){ /*显示增加页面*/
		$customers = $this->get_customers();

		$data['all_customers'] = $customers;
		/*获取区域*/
		$query = $this->db->get('region');
		$data['region'] = $query->result();
		/*获取所有用户*/
		$user_id=$this->session->userdata('id');
		$query = $this->db->select('*')->from('user')->where('id !=',$user_id)->where('user_name !=','何俊斌')->get();
		$data['users'] = $query->result();

		$data ['all_users'] = $this->get_all_users();
		$this->load->view ( 'customer_add',$data);
	}

	public function insert(){
		$data_array = $_POST;
		if(!(trim($data_array['customer_name']))){
// 			redirect ( 'customer/index/' );
			$this->find_error_drop('添加失败,数据不允许为空');
		}else{
			/*检测客户名称是否已经录入*/
			$query = $this->db->query("SELECT count(id) as nums FROM customer where customer_name = '".$data_array['customer_name']."'");
			$row = $query->row_array();
			if($row['nums'] > 0){
// 				redirect ( 'customer/index/' );
				$this->find_error_drop('添加失败,客户名称已经录入');
			}else{
				if(!$data_array['onwer_id']){
					$user_id=$this->session->userdata('id');
					$data_array['user_id'] = $user_id;
				}else{
					$data_array['user_id'] = $data_array['onwer_id'];
				}
				unset($data_array['onwer_id']);
				$time=date('Y-m-d H:i:s', strtotime('now'));
				$data_array['create_time']=$time;

				if(!$data_array['parent_id']){
					$data_array['superior_customer'] = '顶级客户';
				}else{
					/*查询父级客户*/
					$this->db->select('customer_name')->from('customer')->where('id',$data_array['parent_id']);
					$q = $this->db->get();
					$row = $q->row();
					$data_array['superior_customer'] = $row->customer_name;
				}
				$row=$this->db->insert('customer', $data_array);
				if($row > 0){
					redirect ( 'customer/index/' );
				}else{
				}
			}
		}
	}


	public function get_customers($parent_id = 0) {
		$customers = array();

		$q = $this->db->where('parent_id', $parent_id)->get('customer');
		foreach($q->result() as $row){
			$customers[] = $row;
			/*获取子客户*/
			$sub_customers = $this->get_customers($row->id);
			$customers = array_merge($customers, $sub_customers);
		}
		return $customers;
	}

	/*
	 * 查看某条编辑记录
	*/
	public function edit($id = '',$offset = '') {
		$query = $this->db->get_where ( 'customer', array ('id' => $id ) );
		$customers = $this->get_customers();

		$update_data['all_customers'] = $customers;
		$update_data['update_customer'] = $query->row(); /*获取该用户的信息*/
		/*获取区域*/
		$query = $this->db->get('region');
		$update_data['region'] = $query->result();
		/*获取所有用户*/
		$user_id=$this->session->userdata('id');
		$query = $this->db->select('*')->from('user')->where('id !=',$user_id)->where('user_name !=','何俊斌')->get();
		$update_data['users'] = $query->result();

		$update_data ['all_users'] = $this->get_all_users();
		$update_data ['offset'] = $offset;
		$this->load->view ( 'customer_edit', $update_data );
	}

	/*
	 * 编辑某条纪律
	 */
	public function update() {
		$data_array = $_POST; /*接受参数数组*/
		$offset = $data_array['offset'];
		unset($data_array['offset']);
		$customer_name = trim($data_array['customer_name']);
		if(!$customer_name){
// 			redirect ( 'customer/index/' );
			$this->find_error_drop('修改失败,数据不允许为空');
		}else{
			if(!$data_array['region_id']){
				$this->find_error_drop('修改失败,所属区域不允许为空');
			}else{
				if($data_array['parent_id']){ /*获取父级客户名称*/
					$this->db->select('customer_name')->from('customer')->where('id',$data_array['parent_id']);
					$q = $this->db->get();
					$row = $q->row();
					$data_array['superior_customer'] = $row->customer_name;
				}else{
					$data_array['superior_customer'] = '顶级客户';
				}
				$id = $data_array['id'];
				if(!$data_array['user_id']){
					$user_id=$this->session->userdata('id');
					$data_array['user_id'] =$user_id;
				}
				$now_time=date('Y-m-d H:i:s', strtotime('now'));
				$data_array['update_time']=$now_time;
				unset($data_array['id']);
				$user_name=$this->session->userdata('username');
				$data_array['share'] = $data_array['share'];
				
				$this->db->where('id', $id);
				$row=$this->db->update('customer', $data_array);
				
				if($row > 0){
					//redirect ( 'customer/index/' );
					$this->index($offset,'');
				}
			}
		}
	}

	/*新建日程*/
	public function add_schedule($id = ''){
		$now_time=date('Y-m-d', strtotime('now'));
		$data['day']=$now_time;

		$data['show_remind']=1;
		$data['customer_id']=$id;
		$this->load->view ( 'schedule_add',$data );
	}

	/*检测客户的唯一性*/
	public function check_customer(){
		$data_array = $_POST;
		$customer_name = $data_array['name'];
		$query = $this->db->query("SELECT id FROM customer where customer_name = '".$customer_name."'");
		$row = $query->row();
		$id = $row->id;
		if($id){
			echo $id;
		}else{
			echo '';
		}
	}

	/*获取所有用户*/
	public function get_all_users(){
		$query = $this->db->query("SELECT * FROM user order by create_time asc");
		return $query->result();
	}

	public function list_user_customers($id = 0){
		$customers = array();
		if($id == 0){
			redirect ( 'customer/index/' );
		}else{
			$sql = "SELECT * FROM customer WHERE 1=1 and user_id = $id";
		}
		$sql .= " ORDER BY id DESC";

		$query = $this->db->query($sql);
		foreach ($query->result() as $row) {
			$user_query = $this->db->get_where ( 'user', array ('id' => $row->user_id ) );
			$user = $user_query->row();
			$row->user_name = $user->user_name;

			$customers[] = $row;
		}

		return $customers;
	}

	public function get_county(){ /*通过市级获取县级*/
		$data_array = $_POST;
		$parent_id = $data_array['parent_id'];
		$role = $this->session->userdata('role');
		$user_id = $this->session->userdata('id');
		$user_name = $this->session->userdata('username');
		if('经理' == $role || '商务助理' == $role){
			$query = $this->db->query("SELECT id,customer_name FROM customer where parent_id = $parent_id");
		}else{
			$query = $this->db->query("SELECT id,customer_name FROM customer where parent_id = $parent_id and (user_id = $user_id  OR INSTR(`share`, '{$user_name}'))");
		}

		$data = $query->result();
		$json_string = json_encode($data);
		echo $json_string;
	}

	public function city_customers($city_id = '' , $county_id = ''){ /*通过市级获取客户*/
		$customers = array();
		$role = $this->session->userdata('role');
		$user_id = $this->session->userdata('id');
		$user_name = $this->session->userdata('username');
		if($city_id == 0){
			redirect ( 'customer/index/' );
		}else{
			if($county_id){
				$sql = "SELECT * FROM customer WHERE parent_id = $city_id and id = $county_id";
			}else{
				if($role == '市场'){
					$sql = "SELECT * FROM customer WHERE (parent_id = $city_id or id = $city_id) and (user_id = $user_id  OR INSTR(`share`, '{$user_name}'))";
				}else{
					$sql = "SELECT * FROM customer WHERE parent_id = $city_id or id = $city_id";
				}
			}
		}
		$sql .= " ORDER BY id DESC";

		$query = $this->db->query($sql);
		foreach ($query->result() as $row) {
			$user_query = $this->db->get_where ( 'user', array ('id' => $row->user_id ) );
			$user = $user_query->row();
			$row->user_name = $user->user_name;

			$customers[] = $row;
		}

		$data['customer'] = $customers;
		for($o=0;$o<count($customers);$o++){
			$data['customer'][$o]->cus_name_list = 'none';
		}

		$data ['pag_links'] = '';
		$data ['page_title'] = '客户 — 昊美科技CRM系统';
		$data ['class1'] = 'cur';

		$sql = "SELECT * FROM customer WHERE 1=1 and id = $city_id";
		$query = $this->db->query($sql);
		$city_name = $query->row();
		$data ['city_id'] = $city_name->id;
		$data ['county_id'] = $county_id;

		if($role == '市场'){
			$sql = "SELECT id,customer_name FROM customer WHERE parent_id = $city_id and (user_id = $user_id  OR INSTR(`share`, '{$user_name}'))";
		}else{
			$sql = "SELECT id,customer_name FROM customer WHERE parent_id = $city_id";
		}
		$query = $this->db->query($sql);
		$data ['county_customers'] = $query->result();
		$data ['all_users'] = $this->get_all_users();
		$data ['cus_name_list'] = 'none';
		$data ['parent_customers'] = $this->get_parent_customer();

		$cus_count = count($data['customer']);
		$data ['check_cus_pag_links'] = '1';
		$data ['total'] = $cus_count;
		$data ['current_total'] = $cus_count;

		$this->load->view ( 'customer_list', $data );
	}

	public function check_region(){ /*通过客户获取所在地*/
		$data_array = $_POST;
		$customer_id = $data_array['customer_id'];
		$sql = "SELECT region_id FROM customer WHERE id = $customer_id";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		$region_id = $row['region_id'];

		$sql = "SELECT id,district FROM region WHERE id = $region_id";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		$district = $row['district'];
		$region_id = $row['id'];
		$region_array = array('region_id' => $region_id,'district' => $district);
		$json_string = json_encode($region_array);
		echo $json_string;
	}

	public function check_county_customer(){
		$data_array = $_POST;
		$parent_id = $data_array['parent_id'];

		$sql = "SELECT customer.*,user.user_name FROM customer inner join user on customer.user_id = user.id  WHERE parent_id = $parent_id  ORDER BY customer.id DESC";
		$query = $this->db->query($sql);
		$array = $query->result_array();
		$json_string = json_encode($array);
		echo $json_string;
	}

	public function get_parent_customer(){ /*获取市级客户*/
		$role = $this->session->userdata('role');
		if($role == '经理' || $role == '商务助理' ){ /*获取所有市级*/
			$query = $this->db->query("SELECT id,customer_name FROM customer where parent_id = 0 order by create_time desc");
			$customers = $query->result();
		}else{
			$user_id = $this->session->userdata('id');
			$username = $this->session->userdata('username');
			$customers = array();
			$parents = '';
			$sql = "SELECT * FROM customer WHERE 1=1 ";
			if ('经理' <> $role && '商务助理' <> $role) {
				$sql .= " AND user_id = {$user_id}";
				$sql .= " OR INSTR(`share`, '{$username}')";
			}
			$query = $this->db->query($sql);
			$customers = $query->result();

			$last_parent_id = 0;$last_id = 0;
			$parent_id_array = array();
			for($i=0;$i<count($customers);$i++){ /*$customers 所有子级客户*/
				$parent_id = $customers[$i]->parent_id;
				$id = $customers[$i]->id; /*子级客户ID*/
				$parent_id_array[] = $parent_id;
			}
			$count_parent_id_array = count($parent_id_array);
			$data_unique = array_unique($parent_id_array);

			for($i=0;$i<$count_parent_id_array;$i++){
				$id = $data_unique[$i];
				if($id){
					$sql = "select customer.*,user.user_name as user_name from customer inner join user on customer.user_id = user.id where customer.id = $id";
					$county_query = $this->db->query($sql);
					$parents[] = $county_query->result(); /*获取父级客户*/
				}
			}
			if(!$parents){
			}else{
				$data_array = array();
				for($p=0;$p<count($parents);$p++){
					if($parents[$p]){
						$data_array[$p] = $parents[$p][0];
					}else{
						$data_array[$p] = array();
					}
				}
				$customers = $data_array;
			}
			for($y=0;$y<count($customers);$y++){
				if(!$customers[$y]){
					unset($customers[$y]);
				}
			}
		}
		return $customers;
	}
	
	public function console_find_customer($id = ''){
		$this->db->select('*')->from('customer')->where('customer.id', $id);
		$query = $this->db->get();
		/*获取客户区域*/
		foreach ($query->result() as $row){
    		$region_id = $row->region_id;
		}
		if(!$row->region_id){
			$find_data['region_name'] = '未选区域';
		}else{
			$this->db->select('district')->from('region')->where('id', $row->region_id);
			$q = $this->db->get();
			$row = $q->result();
			foreach ($q->result() as $row){
    			$district = $row->district;
			}
			$find_data['region_name'] = $district;
		}

		$find_data['find_customer'] = $query->result();
		/*获取针对该客户的日程*/
		$q = $this->db->select('*')->from('schedule')->where('schedule.customer_id', $id);
		$q = $this->db->get();
		$find_data['find_schedules'] = $q->result();

		/*获取针对该客户的销售机会*/
		$q = $this->db->select('*')->from('opportunity')->where('opportunity.customer_id', $id);
		$q = $this->db->get();
		$find_data['find_opportunitys'] = $q->result();

		/*获取针对该客户的联系人*/
		$q = $this->db->select('*')->from('contacter')->where('contacter.customer_id', $id);
		$q = $this->db->get();
		$find_data['find_contacters'] = $q->result();

		/*获取针对该客户的合同*/
		$q = $this->db->select('customer.customer_name as customer_name,contract.*,opportunity.id as opportunity_id,opportunity.subject as opportunity_subject,user.user_name as user_name')->from('customer')->join('contract', 'contract.customer_id = customer.id')->join('opportunity', 'contract.opportunity_id = opportunity.id')->join('user','contract.owner_id=user.id')->where('contract.customer_id',$id);
		$q = $this->db->get();
		$find_data['find_contracts'] = $q->result();

		//$this->load->view ( 'customer_view', $find_data );
		/*获取区域*/
		$query = $this->db->get('region');
		$find_data['region'] = $query->result();
		/*获取所有用户*/
		$user_id=$this->session->userdata('id');
		$query = $this->db->select('*')->from('user')->where('id !=',$user_id)->where('user_name !=','何俊斌')->get();
		$find_data['users'] = $query->result();
		
		$find_data ['all_users'] = $this->get_all_users();
		
		$customers = $this->get_customers();
		$find_data['all_customers'] = $customers;
		
		
		$this->load->view ( 'console_customer_view', $find_data );
	}
	
}
?>